#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
using namespace std;


#define N 2
#define NUM 1024
void Write(int wfd)
{

    string s="hello,i am child";
    pid_t self=getpid();
    int number=0;
    char buffer[NUM];
    while(true)
    {
        sleep(1);
        buffer[0]=0;
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        cout<<"child set a message"<<endl;

        write(wfd,buffer,strlen(buffer));
        if(number>10) break;
    }
}
void Read(int rfd)
{
    char buffer[NUM];
    int cnt=0;;
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"father read file done"<<endl;
        }
        else break;
        cnt++;
        if(cnt>5) break;
    }

}   
  
int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0)
    {
        perror("pipe");
        return 1;
    }
    //cout<<"pipe[0]:"<<pipefd[0]<<"pipefd[1]:"<<pipefd[1]<<endl;
    pid_t id=fork();
    if(id<0)
    {
        perror("fork");
        return 2;
    }
    else if(id==0) //child
    {
        close(pipefd[0]);
        Write(pipefd[1]);
    }
    // father
    close(pipefd[1]);
    Read(pipefd[0]);
    close(pipefd[0]);
    int status=0;
    pid_t ret=waitpid(id,&status,0);
    if(ret<0) return 3;
    cout<<"wait success:"<<ret<<"exit code:"<<((status>>8)&0xFF)<<"signal code:"<<(status&0x7F)<<endl;
    sleep(5);

    cout<<"father qiut"<<endl;
    return  0;   
}